import Vue from "vue";
import { url, currency } from "@/lib/utils";
import { api } from "@/lib/api";

import { Module } from "vuex";
import { RootState } from "@/types/store";

export interface PkgState {
	/** 套系商品列表 */
	productList: {
		[key: string]: ListWrap<number> & ListReq;
	};
	productMapseries: {
		[pkgId: number]: Pkg.ListItem;
	};
	// 分类
	productMap: {
		[pkgId: number]: Pkg.ListItem;
	};
	productDetailMap: {
		[pkgId: number]: Pkg.Detail;
	};
	productSpecMap: {
		[pkgId: number]: Pkg.Spec[];
	};
	selectedGoodsSpecMap: {
		[pkgId: number]: Pkg.SpecValue[][];
	};
	/** 原始数据 */
	sureGoodsSpecMap: any;
	/** 评价 */
	comments: {
		[pkgId: number]: ListWrap<Pkg.Comment> & ListReq;
	};
	// 门店全部评价
	shopComments: {
		[shopId: number]: ListWrap<Pkg.ShopComment> & ListReq;
	};
	/** 评价数量 count, favorable */
	commentCount: any;
	posterMap: {
		[pkgId: number]: string;
	};
	explosiveList: ListWrap<number> & ListReq;
	/** 返利规则 */
	rebateRule: {
		[pkgId: number]: Pkg.RebateRule;
	};
	discount: {
		[pkgId: number]: {
			full_reduction: Pkg.FullReductionDiscount[];
			gift: Pkg.GiftDiscount[];
			discount: Pkg.DiscountDiscount[];
			balance: Pkg.BalanceDiscount[];
		};
	};
	checkUser: any;
}

const m: Module<PkgState, RootState> = {
	namespaced: true,
	state: {
		/** 套系商品列表 */
		productList: {},
		productMap: {},
		productMapseries: {},
		productDetailMap: {},
		productSpecMap: {},
		selectedGoodsSpecMap: {},
		sureGoodsSpecMap: {},
		/** 评价 */
		comments: {},
		/** 评价数量 count, favorable */
		commentCount: {},

		// 门店全部评价
		shopComments: {},

		posterMap: {},
		explosiveList: {
			list: [],
			loaded: false,
			req: false,
		},
		rebateRule: {},
		discount: {},
		checkUser: false,
	},
	mutations: {
		/**
		 * 设置套系商品列表
		 */
		initProductList(state, key) {
			Vue.set(state.productList, key, {
				list: [],
				req: false,
				loaded: false,
			});
		},
		setProductListReq(state, { key, req }) {
			// if (state.productList[key]) {
			state.productList[key].req = req;
			// }
		},
		setProductListLoaded(state, { key, loaded }) {
			// if (state.productList[key]) {
			state.productList[key].loaded = loaded;
			// }
		},
		// 修改
		concatProductList(state, { key, list, isSwitchTab }) {
			// if (state.productList[key]) {
			let idList = state.productList[key].list;
			// if (!list.length) {
			// 	idList = [];
			//     Vue.set(state.productMap, item.id, item);
			// } else {

			// list.forEach((item) => {
			// 	console.log("item", item);
			// 	idList.push(item.id);
			// 	Vue.set(state.productMap, item.id, item);
			// });
			// }
			if (list.length) {
				list.forEach((item) => {
					idList.push(item.id);
					Vue.set(state.productMap, item.id, item);
				});
				Vue.set(state.productList[key], "list", idList);
			}
			// 边界条件处理，如果请求的商品列表为空
			// else {
			// 	list.forEach((item) => {
			// 		console.log("item", item);
			// 		idList.push(item.id);
			// 		Vue.set(state.productMap, item.id, item);
			// 	});
			// 	Vue.set(state.productList[key], "list", idList);
			// 	// 如果请求列表为空，但不是上拉加载，而是切换新的分类tab后请求
			if (isSwitchTab && !state.productList[key].list.length) {
				idList = [];
				state.productMap = {};
				Vue.set(state.productList[key], "list", []);
				// Vue.set(state.productMap, item.id, {});
			}
			// 	console.log("state.productList111", state.productList, key);
			// 	// idList = [];
			// 	// state.productMap = {};
			// 	// Vue.set(state.productList[key], "list", []);
			// 	// Vue.set(state.productMap, item.id, item);
			// }
			// Vue.set(state.productList[key], "list", idList);
			// }
		},
		/**
		 * 设置爆款套系商品列表
		 */
		initExplosiveList(state) {
			state.explosiveList = {
				list: [],
				req: false,
				loaded: false,
			};
		},
		setExplosiveListReq(state, { req }) {
			state.explosiveList.req = req;
		},
		setExplosiveListLoaded(state, { loaded }) {
			state.explosiveList.loaded = loaded;
		},
		concatExplosiveList(state, { list }) {
			const idList = state.explosiveList.list;
			list.forEach((item) => {
				idList.push(item.id);
				Vue.set(state.productMap, item.id, item);
				Vue.set(state.productMapseries, item.id, item);
			});
			Vue.set(state.explosiveList, "list", idList);
		},
		/** 记录套系详情 */
		setProductDetail(state, { id, detail }) {
			Vue.set(state.productDetailMap, id, detail);
		},
		setProductSpec(state, { id, detail }) {
			Vue.set(state.productSpecMap, id, detail);
		},
		/**
		 * 设置选择规格
		 */
		setSelectedGoodsSpec(state, { id, list }) {
			Vue.set(state.selectedGoodsSpecMap, id, JSON.parse(JSON.stringify(list)));
		},
		/** 重置选择规格 */
		resetSelectedGoodsSpec(state, { id }) {
			Vue.set(
				state.selectedGoodsSpecMap,
				id,
				JSON.parse(JSON.stringify(state.sureGoodsSpecMap[id]))
			);
		},
		setSelectedGoodsSpecItemNumber(state, { id, specIndex, valIndex, number }) {
			Vue.set(
				state.selectedGoodsSpecMap[id][specIndex][valIndex],
				"number",
				number
			);
		},
		/** 确认套餐规格 */
		setSureGoodsSpec(state, { id }) {
			Vue.set(
				state.sureGoodsSpecMap,
				id,
				JSON.parse(JSON.stringify(state.selectedGoodsSpecMap[id]))
			);
		},

		/**
		 * 评论列表
		 */
		initComments(state, pkgId) {
			Vue.set(state.comments, pkgId, {
				list: [],
				loaded: false,
				req: false,
			});
		},
		concatComments(state, { pkgId, list }) {
			state.comments[pkgId].list.push(...list);
		},
		setCommentsLoaded(state, { pkgId, loaded }) {
			state.comments[pkgId].loaded = loaded;
		},
		setCommentsReq(state, { pkgId, req }) {
			state.comments[pkgId].req = req;
		},
		/**
		 * 门店评论列表
		 */
		initShopComments(state, shopId) {
			Vue.set(state.shopComments, shopId, {
				list: [],
				loaded: false,
				req: false,
			});
		},
		concatShopComments(state, { shopId, list }) {
			state.shopComments[shopId].list.push(...list);
		},
		setShopCommentsLoaded(state, { shopId, loaded }) {
			state.shopComments[shopId].loaded = loaded;
		},
		setShopCommentsReq(state, { shopId, req }) {
			state.shopComments[shopId].req = req;
		},

		/**
		 * 记录评价数量信息
		 */
		setCommentCount(state, { pkgId, commentCount }) {
			Vue.set(state.commentCount, pkgId, commentCount);
		},
		/** 记录分享海报 */
		setPoster(state, { pkgId, poster }) {
			Vue.set(state.posterMap, pkgId, poster);
		},
		/** 记录返利规则 */
		setRebateRule(state, { pkgId, rule }) {
			Vue.set(state.rebateRule, pkgId, rule);
		},
		/** 记录优惠信息 */
		setDiscount(state, { pkgId, detail }) {
			Vue.set(state.discount, pkgId, detail);
		},
		setCheckUser(state, data) {
			 state.checkUser = data;
		}
	},
	actions: {
		/**
		 * 获取套系列表 修改
		 * isSwitchTab：切换分类tab为true 上拉加载更多 false
		 */
		async getProductList(
			{ state, commit },
			{
				// brand = null,
				shopId = null,
				category = null,
				offset,
				count,
				sort = null,
				screen = null,
				name = null,
				forceUpdate = false,
				isSwitchTab,
			}
		) {
			// ${brand}_
			const key = `${shopId}_${category}_${sort}_${JSON.stringify(screen)}_${name}`;
			//  新增：如果切换了分类 初始化数据
			if (isSwitchTab) {
				commit("initProductList", key);
			}
			if (!state.productList[key] || (offset === 0 && forceUpdate)) {
				commit("initProductList", key);
			}
			const wrap = state.productList[key];
			if (wrap.loaded || wrap.req) {
				return;
			}
			const length = wrap.list.length;
			const end = offset + count;
			if (end <= length) {
				return;
			}
			if (offset < length) {
				offset = length;
				count = end - length;
			}
			commit("setProductListReq", { key, req: true });
			const data: any = {
				// offset,
				// 如果切换了新的分类 offset初始化为0，如果上拉加载更多，使用累加后的offset
				offset: isSwitchTab ? 0 : offset,
				count,
			};
			// 品牌
			// if(brand){
			// 	data.brand_id = brand;
			// }
			if (shopId) {
				data.shop_id = shopId;
			}
			if (category) {
				data.category = category === "婚纱摄影" ? "婚纱照" : category;
			}
			if (sort) {
				data.sort = sort;
			}
			if (screen) {
				data.screen = screen;
			}
			if (name) {
				data.name = name;
			}
			// TODO 请求参数
			const res = await api.post({
				url: `${url}/api/package`,
				data,
			});
			if (res.statusCode === 200 && res.data.status === 0) {
				const list = res.data.data;
				// TODO 这里的对的
				commit("concatProductList", {
					key,
					list,
					// 新增
					isSwitchTab,
				});
				if (list.length < count) {
					commit("setProductListLoaded", {
						key,
						loaded: true,
					});
				}
			}
			commit("setProductListReq", { key, req: false });
			return res;
		},
		/**
		 * 获得套系详情
		 */
		async getDetail({ state, commit }, { id, forceUpdate }) {
			if (!forceUpdate && state.productDetailMap[id]) {
				return;
			}
			const res = await api.get({
				url: `${url}/api/package/detail`,
				data: {
					id,
				},
			});
			if (res.statusCode === 200 && res.data.status === 0) {
				commit("setProductDetail", {
					id,
					detail: res.data.data,
				});
			}
			return res;
		},
		/**
		 * 获取规格
		 */
		async getProductSpec({ state, commit }, { pkgId, forceUpdate }) {
			if (!forceUpdate && state.productSpecMap[pkgId]) {
				return;
			}
			const res = await api.get({
				url: `${url}/api/package/spec`,
				data: {
					package_id: pkgId,
				},
			});
			if (res.statusCode === 200 && res.data.status === 0) {
				const rdata = res.data.data as Pkg.Spec[];

				// 添加字段
				for (const item of rdata) {
					for (const option of item.values) {
						option.price = currency(option.price);
					}
				}
				const optionList: Pkg.SpecValue[][] = rdata.map((item) => {
					return item.values.map((val) => {
						return {
							...val,
							number: Number(val.number),
						};
					});
				});
				// const newOptionList = optionList.map(item => Object.assign(item, {
				//     number: 1,
				// }));
				commit("setProductSpec", {
					id: pkgId,
					detail: rdata,
				});
				commit("setSelectedGoodsSpec", {
					id: pkgId,
					list: optionList,
				});
				commit("setSureGoodsSpec", {
					id: pkgId,
				});
			}
			return res;
		},

		/**
		 * 获取门店评论列表
		 */
		async getShopComments(
			{ state, commit },
			{ shopId, offset, count, forceUpdate }
		) {
			let wrap = state.shopComments[shopId];
			if (forceUpdate) {
				commit("initShopComments", shopId);
				wrap = state.shopComments[shopId];
			}
			if (!wrap) {
				commit("initShopComments", shopId);
				wrap = state.shopComments[shopId];
			}
			if (wrap.loaded || wrap.req) {
				return;
			}

			const length = wrap.list.length;
			const end = offset + count;
			if (end <= length) {
				return;
			}
			if (offset < length) {
				offset = length;
				count = end - length;
			}
			commit("setShopCommentsReq", { shopId, req: true });
			const res = await api.get({
				url: `${url}/api/shop/comment`,
				data: {
					shop_id: shopId,
					offset,
					count,
				},
			});
			if (res.statusCode === 200 && res.data.status === 0) {
				const list = res.data.data;
				commit("concatShopComments", {
					shopId,
					list,
				});
				if (list.length < count) {
					commit("setShopCommentsLoaded", {
						shopId,
						loaded: true,
					});
				}
			}
			commit("setShopCommentsReq", { shopId, req: false });
			return res;
		},
		/**
		 * 回复门店评论
		 */
		async ShopCommentsSubmit(context, { pid, content }) {
			const res = await api.post({
				url: `${url}/api/shop/reply`,
				data: {
					pid: pid,
					content: content,
				},
			});
			return res;
		},
		/**
		 * 获取普通类商品列表
		 */
		async getComments(
			{ state, commit },
			{ pkgId, offset, count, forceUpdate }
		) {
			let wrap = state.comments[pkgId];
			if (!wrap) {
				commit("initComments", pkgId);
				wrap = state.comments[pkgId];
			}
			if (wrap.loaded || wrap.req) {
				return;
			}

			const length = wrap.list.length;
			const end = offset + count;
			if (end <= length) {
				return;
			}
			if (offset < length) {
				offset = length;
				count = end - length;
			}
			commit("setCommentsReq", { pkgId, req: true });
			const res = await api.get({
				url: `${url}/api/package/comment`,
				data: {
					id: pkgId,
					offset,
					count,
				},
			});
			if (res.statusCode === 200 && res.data.status === 0) {
				const list = res.data.data;
				commit("concatComments", {
					pkgId,
					list,
				});
				if (list.length < count) {
					commit("setCommentsLoaded", {
						pkgId,
						loaded: true,
					});
				}
			}
			commit("setCommentsReq", { pkgId, req: false });
			return res;
		},
		/**
		 * 获取评价数量
		 */
		async getCommentCount(context, { pkgId }) {
			const res = await api.get({
				url: `${url}/api/package/comment_count`,
				data: {
					id: pkgId,
				},
			});
			if (res.statusCode === 200 && res.data.status === 0) {
				context.commit("setCommentCount", {
					pkgId,
					commentCount: res.data.data,
				});
			}
			return res;
		},
		/** 获取海报 */
		async getPoster({ state, commit }, { pkgId }) {
			if (state.posterMap[pkgId]) {
				return;
			}
			const res = await api.get({
				url: `${url}/api/package/poster`,
				data: {
					id: pkgId,
				},
			});
			if (res.statusCode === 200 && res.data.status === 0) {
				commit("setPoster", {
					pkgId,
					poster: res.data.data,
				});
			}
			return res;
		},
		/** 添加访问量 */
		async addVisitor({ state, commit }, { pkgId }) {
			const res = await api.get({
				url: `${url}/api/package/visitor`,
				data: {
					package_id: pkgId,
				},
			});
			return res;
		},
		/** 添加分享量 */
		async addShare({ state, commit }, { pkgId }) {
			const res = await api.get({
				url: `${url}/api/package/share`,
				data: {
					package_id: pkgId,
				},
			});
			return res;
		},
		/**
		 * 获取爆款套系列表
		 */
		async getExplosiveList(
			{ state, commit },
			{ offset, count, forceUpdate = false }
		) {
			if (!state.explosiveList || (offset === 0 && forceUpdate)) {
				commit("initExplosiveList");
			}
			const wrap = state.explosiveList;
			if (wrap.loaded || wrap.req) {
				return;
			}
			const length = wrap.list.length;
			const end = offset + count;
			if (end <= length) {
				return;
			}
			if (offset < length) {
				offset = length;
				count = end - length;
			}
			commit("setExplosiveListReq", { req: true });
			const data = {
				offset,
				count,
			};
			const res = await api.get({
				url: `${url}/api/package/explosive`,
				data,
			});
			if (res.statusCode === 200 && res.data.status === 0) {
				const list = res.data.data;
				commit("concatExplosiveList", {
					list,
				});
				if (list.length < count) {
					commit("setExplosiveListLoaded", {
						loaded: true,
					});
				}
			}
			commit("setExplosiveListReq", { req: false });
			return res;
		},
		/**
		 * 获取返利规则
		 */
		async getRebateRule(context, { pkgId }) {
			const response = await api.get({
				url: `${url}/api/package/rebate_rule`,
				data: {
					id: pkgId,
				},
			});
			const rdata = response.data;
			if (response.statusCode === 200 && rdata.status === 0) {
				context.commit("setRebateRule", {
					pkgId,
					rule: rdata.data,
				});
			}
			return rdata;
		},
		/**
		 * 获取优惠信息
		 */
		async getDiscount(context, { pkgId, referrer }) {
			const response = await api.get({
				url: `${url}/api/package/discount`,
				data: {
					id: pkgId,
					share_user_id: referrer,
				},
			});
			const rdata = response.data;
			if (response.statusCode === 200 && rdata.status === 0) {
				context.commit("setDiscount", {
					pkgId,
					detail: rdata.data,
				});
			}
			return rdata;
		},
		/**
		 * 查询是否所属集团
		 */
		async getCheckUser(context, { user_id, shop_id }) {
			const response = await api.get({
				url: `${url}/api/package/check_user`,
				data: {
					user_id,
					shop_id,
				},
			});
			const rdata = response.data;
			if (response.statusCode === 200 && rdata.status === 0) {
				context.commit("setCheckUser", rdata.data);
			}
			return rdata;
		},
	},
};

export default m;
